<template>
  <!-- 承运商对账单汇总 -->
  <div>
    <div
      class="shareContainer"
      ref="shareContainer"
      v-show="checkType === ''"
      v-loading="loadingStatus"
    >
      <!-- <el-tabs
        class="tab"
        type="border-card"
        v-model="activeName"
        @tab-click="displayOrders"
      >
        <el-tab-pane label="对账列表" name="first"></el-tab-pane>
        <el-tab-pane label="已取消" name="fifth"></el-tab-pane>
      </el-tabs> -->
      <div class="content-wrapper">
        <div class="actions" style="padding-bottom: 10px">
          <div class="left">
            <!-- <el-button
              @click="cancelCheckPage"
              plain
              type="primary"
              v-show="activeName !== 'fifth'"
              data-tracker="P50-4"
              v-permission="'finance_customer_delete'"
              >取消对账</el-button
            > -->
            <el-button
              @click="exportDerive()"
              plain
              type="primary"
              data-tracker="P50-4"
              v-permission="'finance_customer_delete'"
              >导出</el-button
            >
          </div>
          <div class="right" style="display: flex">
            <el-button
              type="primary"
              size="mini"
              @click="resultClickFn"
              style="margin: 0px 10px 0px 0px"
              >重置
            </el-button>
            <SettinUp
              :settype="headerId"
              :objSettinUpdata="objSettinUp"
              :key="activeName"
            ></SettinUp>
          </div>
        </div>
        <!-- 表格 -->
        <div class="table" v-if="header_data_list.length > 0" :key="activeName">
          <TableHeader
            ref="TableHeaderList"
            :header_data_list="header_data_list"
            :HeaderData="HeaderData"
            :propMap="propMap"
            :redact="''"
            :particulars="''"
            :objheader="objheader"
            @orderIdNumsEvent="handleDeleteType"
            :operation_type="3"
            fixedWidth="300"
          >
            <template #operation="{ scope }" v-if="activeName === 'first'">
              <!-- 接收内容：{{ scope }} -->
              <el-button
                type="text"
                plain
                size="mini"
                style=""
                @click="clickToDetail(scope.row.id)"
                data-tracker="P49-5"
                >详情
              </el-button>
              <el-button
                v-show="['0', '1', '3'].includes(scope.row.account_status)"
                type="text"
                plain
                size="mini"
                style=""
                @click="editCheckDetail(scope.row)"
                data-tracker="P49-5"
                >调账
              </el-button>
              <el-button
                v-show="['0'].includes(scope.row.account_status)"
                type="text"
                plain
                size="mini"
                data-tracker="P49-3"
                @click="sendCheckPage(scope.row)"
                >发送对账单
              </el-button>
              <el-button
                v-show="['0', '1'].includes(scope.row.account_status)"
                type="text"
                plain
                size="mini"
                @click="adoptCheck(scope.row)"
                data-tracker="P49-6"
                >对账通过
              </el-button>
              <el-button
                v-show="['1'].includes(scope.row.account_status)"
                type="text"
                plain
                size="mini"
                @click="unusualCheck(scope.row)"
                data-tracker="P49-7"
                >对账异常
              </el-button>
              <!-- <el-button type="text" plain size="mini" @click="handleClickEdit(scope.row)">申请付款
              </el-button> -->
              <el-button
                v-show="
                  ['2'].includes(scope.row.account_status) &&
                  scope.row.ap_status === '0' && scope.row.type === '1'
                "
                type="text"
                plain
                size="mini"
                @click="applyForPayment(scope.row)"
                data-tracker="P49-7"
                >申请付款
              </el-button>
              <el-button
              type="text"
              plain
              size="mini"
              style=""
              @click="cancelCheckPage(scope.row.id)"
              data-tracker="P49-5"
              v-show=" scope.row.account_status != 2"
              >删除
            </el-button>
              <el-button
              type="text"
              plain
              size="mini"
              style=""
              @click="deriveExprot(scope.row.id)"
              data-tracker="P49-5"
              >导出
            </el-button>
            <!-- 新增 -->
          
            <el-button
              v-show="['2'].includes(scope.row.account_status)&&
              scope.row.ap_status === '0'
              "
              type="text"
              plain
              size="mini"
              style=""
              @click="CustomerCancle(scope.row.id)"
              data-tracker="P49-5"
              >取消通过
            </el-button>
            </template>
          </TableHeader>
        </div>
        <!-- <el-table
          :data="orders"
          ref="multipleTable"
          style="width: 100%"
          class="talbeorder"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45"> </el-table-column>
          <el-table-column
            prop=""
            label="序号"
            width="50"
            type="index"
          ></el-table-column>
          <el-table-column prop="account_no" label="对账单号" width="120">
            <template slot-scope="scope">
              <div
                @click="clickToDetail(scope.row.id)"
                style="cursor: pointer; color: blue"
              >
                {{ scope.row.account_no }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="account_customer_name"
            label="承运商名称"
            width="240"
          >
          </el-table-column>
          <el-table-column prop="is_adjust" label="是否调账" width="80">
            <template slot-scope="scope">
              {{ scope.row.is_adjust === "1" ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="activeName === 'third'"
            prop="ap_status"
            label="审批状态"
            width="100"
          >
            <template slot-scope="scope">
         
              {{
                ["待审批", "审批中", "待付款", "已付款"][scope.row.ap_status]
              }}
            </template>
          </el-table-column>
          <el-table-column prop="now_price" label="对账金额" width="120">
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="140">
          </el-table-column>
          <el-table-column prop="type" label="创建人类型" width="140">
            <template slot-scope="scope">
              {{ scope.row.type === "0" ? "发货客户" : "承运商" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="创建对账单时间"
            width="240"
          >
            <template slot-scope="scope">
              {{
                new Date(Number(scope.row.create_time) * 1000)
                  .toLocaleString()
                  .replace(/:\d{1,2}$/, " ")
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            width="300"
          ></el-table-column>
 
        </el-table>  -->
        <div class="actions" style="padding-top: 10px; width: 100%">
          <div class="left"></div>
          <div class="right">
            <el-pagination
              small
              background
              :current-page="paginations.pageIndex"
              :page-sizes="paginations.pageSizes"
              :page-size="paginations.pageSize"
              :layout="paginations.layout"
              :total="paginations.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <div v-show="checkType === 'edit' || checkType === 'info'">
      <carrierCheckDetail></carrierCheckDetail>
    </div>
    <div>
      <paymentDialog
        ref="paymentDialog"
        :account_id="selectedDetails[0] ? selectedDetails[0].id : account_id"
        :carrier_id="
          selectedDetails[0] ? selectedDetails[0].account_customer_id : ''
        "
        :carrier_name="
          selectedDetails[0] ? selectedDetails[0].account_customer_name : ''
        "
        :now_price="selectedDetails[0] ? selectedDetails[0].now_price : ''"
      ></paymentDialog>
    </div>
  </div>
</template>

<script>
import TableHeader from "@/page/orderform/components/TableHeader/tableheader.vue";
import SettinUp from "@/page/orderform/components/settingUp/settingUp.vue";
import pagination from "@/components/pagination";
import paymentDialog from "./paymentDialog.vue";
import carrierCheckDetail from "../customerlist/carrierCheckDetail.vue";
import {
  getCarrierCheckedList,
  reqSendCarrierCheckPage,
  deleteCarrierCheck,
  reqAdoptCarrierCheck,
  reqUnusualCarrierCheck,
  reqPaymentInfo, //为了判断对账单是否已申请付款
  finance_carriers_list_export, //导出
  reqOutPutCarrier,
  finance_carrier_cancel
} from "@/api/finance";
export default {
  data() {
    return {
      loadingStatus: false,
      selectAreaVisible: true, //这个是筛选那一行
      activeName: "first", //汇总的tabs切换
      carrierList: [], //承运商名称
      account_id: "", //对账单id
      searchData: {
        checkNumber: "", //对账单号
        carrier_id: "", //承运商名称
        createTime: [], //创建时间
      }, //查询条件
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pageNum: 1, //目前在第几页
      totalListNum: 10, //列表总数
      pageSize: 20, //一页多少条
      orders: [],
      selectedOrders: [],
      selectedDetails: [],
      detailsTime: [], //明细运单的开单时间,要给传给check组件
      toCheck: false,
      operationType: false, //true是查看详情,false是修改
      maxheight: 600,
      header_data_list: [],
      propMap: {},
      obj_list: {},
      HeaderData: [],
      waybillIdNums: [],
      operation_type: 0,
      dynParams: {},
      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [10, 20, 50, 100], //每页显示多少条
        total: 200,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      searchParams: {},
    };
  },
  components: {
    pagination,
    carrierCheckDetail,
    paymentDialog,
    TableHeader,
    SettinUp,
  },
  mounted() {
    // this.lastMonthTimetamp();

    this.$store.commit("CHANGE_CHECK_TYPE", "");
    this.$store.commit("CHANGE_OPERATE_TYPE", "");
    this.displayOrders(); 
    this.$nextTick(() => {
      if (this.$route.query.id) {
        this.clickToDetail(this.$route.query.id);
      }
    })
  
    if (this.$store.getters.carrierList.length === 0) {
      this.$store.dispatch("getCarrierList");
    }
  },
  watch: {
    $route: {
      handler(newV, oldV) {
        if (this.$route.query.type == 0) {
          this.activeName = "first";
          this.displayOrders();
        } else if (this.$route.query.type == 1) {
          this.activeName = "fifth";
          this.displayOrders();
        }
        // console.log(this.$route.query.type, "this.$route.query.type");
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    checkType() {
      return this.$store.getters.checkType;
    },
    headerId() {
      return "50";
    },
  },
  methods: {
    resultClickFn() {
      this.paginations.pageIndex = 1;
      this.paginations.pageSize = 20;
      this.$refs.TableHeaderList.childMethod();
    },
    objSettinUp() {
      this.displayOrders();
    },
    async displayOrders(setHeader = true) {
      // const { pageNum, pageSize, searchData } = this;
      const params = {
        // account_no: String(searchData.checkNumber),
        // account_customer_id: String(searchData.carrier_id),
        // account_status:
        //   this.activeName === "first"
        //     ? "0"
        //     : this.activeName === "second"
        //       ? "1"
        //       : this.activeName === "third"
        //         ? "2"
        //         : this.activeName === "fourth"
        //           ? "3"
        //           : "", //对账单的状态 0待对账 1对账中 2对账通过 3对账异常
        is_deleted: this.activeName === "fifth" ? "1" : "", //1是获取已取消列表
        // start_time:
        //   searchData.createTime !== null && searchData.createTime[0]
        //     ? String(parseInt(searchData.createTime[0] / 1000))
        //     : "",
        // end_time:
        //   searchData.createTime !== null && searchData.createTime[1]
        //     ? String(parseInt(searchData.createTime[1] / 1000))
        //     : "",
        page: this.paginations.pageIndex + "",
        page_size: this.paginations.pageSize + "",
        header_id: this.headerId + "",
        ...this.searchParams,
      };
      this.dynParams = params;
      let result = await getCarrierCheckedList(params);
      this.orders = result.data.data || [];
      this.paginations.total = result.data.pagination.total * 1;
      this.orders.unshift({});
      this.header_data_list = this.orders;
      if (setHeader) {
        this.HeaderData = result.data.item_list;
        this.Fntransformation(this.HeaderData);
      }
    },
    objheader(obj) {
      this.paginations.pageIndex = 1;
      this.searchParams = obj;
      this.displayOrders(false);
    },
    Fntransformation(obj) {
      const result = {};
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          if (obj[prop].send_name !== "") {
            result[obj[prop].name] = obj[prop].show_name;
          } else {
            result[obj[prop].name] = obj[prop].name;
          }
        }
      }
      this.propMap = result;
    },
    handleDeleteType(ids, val) {
      this.handleSelectionChange(val);
    },
    resettingData() {
      Object.assign(this.$data.searchData, this.$options.data().searchData);
      this.displayOrders();
    },
    async getCarrierList() {
      this.carrierList = this.$store.getters.carrierList;
    },
    selectedWebsite(id) {
      //选择网点
      let piece = this.websiteList.find((item) => item.id === id);
      this.searchData.website = piece.id;
    },
    searchSenderCheckList() {
      this.displayOrders();
    },
    handleSizeChange(val) {
      this.paginations.pageSize = val; //一页多少条
      this.displayOrders();
    },
    handleCurrentChange(val) {
      this.paginations.pageIndex = val; //第多少页
      this.displayOrders();
    },
    clickToDetail(id) {
      // console.log(id, "idjflkasjdlkjldi");
      this.loadingStatus = true;
      this.$store.commit("GET_CHECK_DETAIL_ID", id);
      this.$store.commit("CHANGE_CHECK_TYPE", "info");
      setTimeout(() => {
        this.loadingStatus = false;
      }, 500);
    },
    handleSelectionChange(checked) {
      this.selectedOrders = checked.map((item) => item.id);
      this.selectedDetails = checked;
    },
    editCheckDetail(row) {
      //创建对账单,判断一下所选订单的对账状态,已对过账的提醒一下
      this.$store.commit("GET_CHECK_DETAIL_ID", row.id);
      this.$store.commit("CHANGE_CHECK_TYPE", "edit");
    },
    async sendCheckPage(row) {
      //发送对账单
      let result = await reqSendCarrierCheckPage({
        id: String(row.id),
      });
      if (result.code === 10000) {
        this.$message({
          type: "success",
          message: "发送对账单",
        });
        this.displayOrders();
      }
    },
    async cancelCheckPage(value) {
      //取消对账
      // if (this.selectedOrders.length === 1) {
       
      // } else {
      //   this.$message({
      //     type: "error",
      //     message: "只能选择一个对账单进行操作",
      //   });
      // }
      let result = await deleteCarrierCheck({
          id: String(value),
        });
        if (result.code === 10000) {
          this.$message({
            type: "success",
            message: "对账单删除成功",
          });
          this.displayOrders();
        }
    },
    async adoptCheck(row) {
      //对账通过
      let result = await reqAdoptCarrierCheck({
        id: String(row.id),
      });
      if (result.code === 10000) {
        this.$message({
          type: "success",
          message: "对账通过",
        });
        this.displayOrders();
      }
    },
    async unusualCheck(row) {
      //对账异常
      let result = await reqUnusualCarrierCheck({
        id: String(row.id),
      });
      if (result.code === 10000) {
        this.$message({
          type: "success",
          message: "对账异常",
        });
        this.displayOrders();
      }
    },
    async applyForPayment(row) {
      if (row.ar_status == 0) {
        this.$router.push({
          name: "thecarrierPaysadd",
          query: {
            Type: 0,
            id: row.id,
            account_customer_name: row.account_customer_name,
            account_no: row.account_no,
            now_price: row.now_price,
            account_customer_id: row.account_customer_id,
            TageType: 0,
          },
        });
      } else {
        this.$message({
          type: "error",
          message: "承运商已申请付款请勿重复操作",
        });
      }
    },
    async handleClickEdit(row) {
      //编辑付款，判断审批状态再进行编辑这个后面做
      this.account_id = row.id;
      let result = await reqPaymentInfo({
        account_id: this.account_id * 1,
      });
      if (result.code === 10000 && result.data !== null) {
        this.$store.commit("CHANGE_OPERATE_TYPE", "edit");
        this.selectedDetails = [row];
        this.$refs.paymentDialog.dialogVisible = true;
      } else {
        this.$message({
          type: "error",
          message: "请先申请付款",
        });
      }
    },
    lastMonthTimetamp() {
      //  一天的秒数
      const MillisecondsADay = 24 * 60 * 60;

      const date = new Date();
      date.setDate(1);
      date.setHours(0, 0, 0, 0);
      //  当月开始时间戳
      const timeStamp = date.getTime() / 1000;
      //  上个月的天数
      const days = this.lastMonthDats();
      //  上月开始时间戳
      const lastMonthStart = timeStamp - MillisecondsADay * days;
      //  上月结束时间戳
      const lastMonthEnd = timeStamp - 1;
      this.searchData.createTime = [lastMonthStart * 1000, lastMonthEnd * 1000];
    },
    lastMonthDats() {
      const date = new Date();
      const year = date.getFullYear();
      //  上个月月份
      let month = date.getMonth() + 1 - 1; //  0-11 表示 1月-12月
      //  0 表示12月
      month = month || 12;
      //  30天的月份
      const arr30 = [4, 6, 9, 11];
      //  31天的月份
      const arr31 = [1, 3, 5, 7, 8, 10, 12];
      if (arr30.indexOf(month) !== -1) {
        //  上个月是 30 天
        return 30;
      } else if (arr31.indexOf(month) !== -1) {
        //  上个月是 31 天
        return 31;
      } else {
        //  2月
        if (this.isRunYear(year)) {
          return 29;
        } else {
          return 28;
        }
      }
    },
    isRunYear(year) {
      //  条件:能被4整除并且不能被100整除，或者被400整除的
      let flag = false;
      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        flag = true;
      }
      return flag;
    },
    exportDerive() {
      var params = {
        is_deleted: this.activeName === "fifth" ? "1" : "", //1是获取已取消列表
        header_id: this.headerId + "",
        ...this.searchParams,
      };
      finance_carriers_list_export(params).then((res) => {
        this.reqUrl = "https://" + res.data.url;
        window.open(this.reqUrl);
      });
    },
    async deriveExprot(ids) {
      let result = await reqOutPutCarrier({
        id: ids * 1,
      });
      if (result.code === 10000) {
        window.open("https://" + result.data.loaded_url, "_self");
        this.$message({
          type: "success",
          message: "导出成功",
        });
      } else {
        this.$message({
          type: "error",
          message: result.message,
        });
      }
    },
    CustomerCancle(value) {
      var param = {
        id: value+"",
      };
      finance_carrier_cancel(param).then((res) => {
        if (res.code == 10000) {
          this.$message({
            message: "取消通过成功",
            type: "success",
          });
          this.displayOrders();
        }
      });
    },
    subcomponent() {
      this.displayOrders();
    }

  },
};
</script>

<style lang="less" scoped>
// /deep/ .el-tabs__nav-wrap {
//   left: -178px;
// }
.shareContainer {
  padding: 10px 15px;
  background-color: #fff;

  .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }

  .operation {
    // height: 40px;

    .el-button {
      margin-left: 0px;
      margin-right: 10px;
    }

    ::v-deep .el-pagination {
      float: right;
      margin: 0px 0px 0px 20px;

      .el-input--mini .el-input__inner {
        height: 24px;
      }
    }
  }

  /* /deep/ .content-wrapper .el-table {
    position:static
  } */
  /deep/ .el-tabs--border-card > .el-tabs__content {
    padding: 0px;
  }

  /deep/ .content-wrapper .el-table__header {
    width: 100% !important;
    table-layout: fixed;
  }

  /deep/ .content-wrapper .el-table__body {
    width: 100% !important;
  }

  .content-wrapper {
    // padding: 15px;
  }

  .tab.el-tabs--border-card {
    border: none;
    box-shadow: none;

    .el-tabs__content {
      padding: 0;
      height: 40px;
    }
  }
}
.actions {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  background-color: #fff;

  .el-button + .el-dropdown,
  .el-dropdown + .el-button {
    margin-left: 10px;
  }
}
</style>